package com.zsd.android.okhttplib.chain;

import com.zsd.android.okhttplib.Call;
import com.zsd.android.okhttplib.RealCall;
import com.zsd.android.okhttplib.Request;
import com.zsd.android.okhttplib.Response;

import java.io.IOException;
import java.util.List;

/**
 * 责任节点任务管理器
 */
public class ChainManager implements Chain {

    private List<Interceptor> interceptors;
    private int index;
    private Request request;
    private RealCall call;

    public ChainManager() {}

    public ChainManager(List<Interceptor> interceptors, int index, Request request, RealCall call) {
        this.interceptors = interceptors;
        this.index = index;
        this.request = request;
        this.call = call;
    }

    @Override
    public Request getRequest() {
        return request;
    }

    @Override
    public Response getResponse(Request request) throws IOException {
        if (index >= interceptors.size()) {
            throw new AssertionError();
        }
        if (interceptors.isEmpty()) {

        }
        Interceptor interceptor = interceptors.get(index);
        ChainManager manager = new ChainManager(interceptors, index + 1, request, call);
        Response response = interceptor.doNext(manager);
        return response;
    }

    public List<Interceptor> getInterceptors() {
        return interceptors;
    }

    public int getIndex() {
        return index;
    }

    public RealCall getCall() {
        return call;
    }
}
